package com.zhoufeng.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.json.GsonUtil;
import com.github.abel533.echarts.series.Gauge;
import com.github.abel533.echarts.series.gauge.Detail;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.zhoufeng.common.Util;
import com.zhoufeng.common.bean.CommonMsgBean;
import com.zhoufeng.interceptor.SessionInteceptor;
import com.zhoufeng.model.DeviceConfigure;
import com.zhoufeng.model.DeviceModel;
import com.zhoufeng.model.User;
import com.zhoufeng.model.UserDeviceModel;

@Before(SessionInteceptor.class)
public class IndexController extends Controller {
	private static final Logger logger = Logger.getLogger(IndexController.class);

	@ClearInterceptor(ClearLayer.ALL)
	public void loginAction() {
		User user = getModel(User.class);
		User dbUser = User.me.findByAccount(user);

		String enPassword = Util.encryptBasedDes(user.getStr("password"));
		CommonMsgBean msg = new CommonMsgBean();
		if (dbUser == null) {
			msg.setMsg("用户不存在！");
		} else if (dbUser != null && dbUser.getStr("password").equals(enPassword)) {
			setSessionAttr("userinfo", dbUser);
			setSessionAttr("username", dbUser.getStr("username"));
			setSessionAttr("isadmin", dbUser.getInt("isadmin"));
			msg.setFlag(true);
			msg.setMsg("登陆成功！");
			logger.debug("用户：" + dbUser.getStr("username") + "，用户编号：" + dbUser.getStr("userid") + "，登陆成功！");
		} else {
			msg.setMsg("密码错误！");
		}
		renderJson(msg);
	}

	public void index() {
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "数据显示");
		render("index.html");
	}

	public void loginSuccess() {
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "数据显示");
		render("index.html");
	}

	public void loginOut() {
		setSessionAttr("userinfo", null);
		setSessionAttr("username", null);
		render("login.html");
	}

	public void getData() {

		// List<Record> devices =
		// Db.find("select b.*,a.* from thing_device a inner join thing_user_device b on a.id = b.deviceid where b.userid = '"
		// + sessionuser.getStr("userid") + "'");
		List<Record> devices  = null;
		User sessionuser = (User) getSession().getAttribute("userinfo");
		int isadmin = (int) sessionuser.getInt("isadmin");
		if(isadmin == 1){
			devices = Db.find("select a.*,(select devicename from thing_user_device where deviceid = a.id limit 1) devicename from thing_device a order by a.onoroff desc, a.id asc ");
		}else{
			devices = Db.find("select a.*,(select devicename from thing_user_device where deviceid = a.id limit 1) devicename from thing_device a inner join thing_user_device b on a.id = b.deviceid where b.userid = ? order by a.onoroff desc, a.id asc ",sessionuser.getStr("userid"));
		}
		// List<DeviceModel> devices =
		// DeviceModel.me.find("select a.* from thing_device a inner join thing_user_device b on a.id = b.deviceid where b.userid = '"+sessionuser.getStr("userid")+"'");
		List<Map<String, Object>> infos = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < devices.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			Record model = devices.get(i);
			
			
			String deviceid = model.get("id");
			
			String first = deviceid.substring(0,2);
			Integer firstnum = Integer.parseInt(first, 16) * 256 * 256;
			String second = deviceid .substring(2,4);
			Integer secondnum = Integer.parseInt(second, 16) * 256;
			String three = deviceid.substring(4,6);
			Integer threenum = Integer.parseInt(three, 16);
			
			String idint = new Integer(firstnum + secondnum + threenum).toString();

			map.put("id", model.get("id"));
			map.put("devicename", (model.get("devicename") == null ? model.get("id") : model.get("devicename")));
			map.put("devicename", (idint));
			int onoroff = model.getInt("onoroff");

			if (onoroff == 1) {

				map.put("recievedate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(model.getStr("recievedate")))));
				map.put("frequency", new Integer(model.getStr("frequency")));
				map.put("formaldehyde", new Integer(model.getStr("formaldehyde")));
				map.put("mode", new Integer(model.getStr("mode")));
				map.put("modeswitch", new Integer(model.getStr("modeswitch")));
				map.put("pm25in", new Integer(model.getStr("pm25in")));
				map.put("pm25out", new Integer(model.getStr("pm25out")));
				map.put("co2", new Integer(model.getStr("co2")));
				map.put("enteringairtempin", new Integer(model.getStr("enteringairtempin")));
				map.put("leavingairtempin", new Integer(model.getStr("leavingairtempin")));
				map.put("enteringairtempout", new Integer(model.getStr("enteringairtempout")));
				map.put("leavingairtempout", new Integer(model.getStr("leavingairtempout")));
				map.put("humidity", new Integer(model.getStr("humidity")));

				int pm25in = new Integer(model.getStr("pm25out"));

				if (pm25in <= 35) {
					map.put("roomstyle", "room1");
				} else if (pm25in <= 75) {
					map.put("roomstyle", "room2");
				} else if (pm25in <= 115) {
					map.put("roomstyle", "room3");
				} else if (pm25in <= 150) {
					map.put("roomstyle", "room4");
				} else if (pm25in <= 250) {
					map.put("roomstyle", "room5");
				} else {
					map.put("roomstyle", "room6");
				}
				
//				Option option = new Option();
//		        option.tooltip().formatter("{a} : {c}");
//		        option.toolbox().show(false).feature(Tool.mark, Tool.restore, Tool.saveAsImage).setBorderWidth(1);
//		        option.series(new Gauge("pm25值").detail(new Detail().formatter("{value}")).data(new Data("pm25值", pm25in)));
//				
		        map.put("pm25inoption", true);
				

			} else {
				map.put("recievedate", "--");
				map.put("frequency", "--");
				map.put("formaldehyde", "--");
				map.put("mode", "--");
				map.put("modeswitch", "--");
				map.put("pm25in", "--");
				map.put("pm25out", "--");
				map.put("co2", "--");
				map.put("enteringairtempin", "--");
				map.put("leavingairtempin", "--");
				map.put("enteringairtempout", "--");
				map.put("leavingairtempout", "--");
				map.put("humidity", "--");

				map.put("roomstyle", "roomOffline");
			}
			infos.add(map);
		}
		renderJson(infos);
	}

	public void directToChartPage() {
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		String id = getPara(0);
		String type = getPara(1, "pm25in");
		String uid = (String) getSession().getAttribute("uid");
		uid = uid == null ? "1" : uid;
		setAttr("id", id);
		setAttr("type", type);
		setAttr("uid", uid);
		render("showdatachart.html");
	}

	public void getFlowData() {

		String inpara = getPara("machine");// 查询机器
		String[] inmachine = inpara.split(";");
		String inpara2 = getPara("type");// 查询类型
		List<String> idList = new ArrayList<String>();
		List<List<Date>> dates = new ArrayList<List<Date>>();

		List<Map<String, List<Integer>>> datas = new ArrayList<Map<String, List<Integer>>>();

		for (String machineid : inmachine) {
			Map<String, List<Integer>> data = new HashMap<String, List<Integer>>();

			Page<DeviceModel> page = DeviceModel.me.paginate(1, 30, "select * ", "from thing_device_alldata where  id='" + machineid + " ' order by recievedate asc");
			List<DeviceModel> devices = page.getList();

			List<Date> dateList = new ArrayList<Date>();
			List<Integer> pm25inList = new ArrayList<Integer>();
			List<Integer> pm25outList = new ArrayList<Integer>();
			List<Integer> co2List = new ArrayList<Integer>();
			List<Integer> formaldehydeList = new ArrayList<Integer>();
			List<Integer> enteringairtempinList = new ArrayList<Integer>();
			List<Integer> leavingairtempinList = new ArrayList<Integer>();
			List<Integer> enteringairtempoutList = new ArrayList<Integer>();
			List<Integer> leavingairtempoutList = new ArrayList<Integer>();
			List<Integer> humidityList = new ArrayList<Integer>();

			for (int i = 0; i < devices.size(); i++) {
				DeviceModel device = devices.get(i);
				dateList.add(new Date(new Long(device.getStr("recievedate"))));
				pm25inList.add(new Integer(device.getStr("pm25in")));
				pm25outList.add(new Integer(device.getStr("pm25out")));
				co2List.add(new Integer(device.getStr("co2")));
				formaldehydeList.add(new Integer(device.getStr("formaldehyde")));
				enteringairtempinList.add(new Integer(device.getStr("enteringairtempin")));
				leavingairtempinList.add(new Integer(device.getStr("leavingairtempin")));
				enteringairtempoutList.add(new Integer(device.getStr("enteringairtempout")));
				leavingairtempoutList.add(new Integer(device.getStr("leavingairtempout")));
				humidityList.add(new Integer(device.getStr("humidity")));
			}

			dates.add(dateList);

			data.put("pm25in", pm25inList);
			data.put("pm25out", pm25outList);
			data.put("co2", co2List);
			data.put("formaldehyde", formaldehydeList);
			data.put("enteringairtempin", enteringairtempinList);
			data.put("leavingairtempin", leavingairtempinList);
			data.put("enteringairtempout", enteringairtempoutList);
			data.put("leavingairtempout", leavingairtempoutList);
			data.put("humidity", humidityList);
			datas.add(data);

			idList.add(machineid);

		}

		// 例子：http://echarts.baidu.com/doc/example/line.html
//		EnhancedOption option = new EnhancedOption();
//		option.tooltip().trigger(Trigger.axis);
//		option.legend(idList.toArray());
//		option.toolbox().show(false);
//		option.calculable(true);
//		option.xAxis(new CategoryAxis().boundaryGap(false).data(dates.get(0).toArray()));
//		List<Object> data = new ArrayList<Object>();
//		data.add(0);
//		data.add(37);
//		data.add(75);
//		data.add(115);
//		data.add(150);
//		data.add(250);
//		data.add(500);
//		ValueAxis axis = new ValueAxis();
//		axis.setData(data);
//		option.yAxis(axis);
//
//		for (int i = 0; i < idList.size(); i++) {
//			option.series(new Line().smooth(true).name(idList.get(i)).stack("总量").symbol(Symbol.emptyCircle).data(datas.get(i).get(inpara2).toArray()));
//		}
//
//		renderJson(option.toString());
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void getUserMachineInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Record> devices = null;
		User sessionUser = (User) getSession().getAttribute("userinfo");
		if (sessionUser == null) {
			String deviceid = getPara("deviceid");
			devices = Db.find("select ifnull((select devicename from thing_user_device where deviceid = a.id limit 1),a.id)   devicename,a.* from thing_device a where a.id =  ?  ", deviceid);
		} else {
			devices = Db.find("select ifnull((select devicename from thing_user_device where deviceid = a.id and userid = ? limit 1),a.id)  devicename,a.* from thing_device a ",sessionUser.getStr("userid") );
		}
		map.put("status", "ok");
		map.put("result", devices);
		renderJson(map);
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void getDataForHiChart() throws ParseException {
		String fun = getPara("fun");
		// String type = getPara("type");
		String sn = getPara("sn");
		sn = "('" + sn.replaceAll(",", "','") + "')";
		User sessionUser = (User) getSession().getAttribute("userinfo");
		int time = 24;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
		if ("get24hData".equals(fun)) {
			time = 24;
			format = new SimpleDateFormat("yyyyMMddHH");
		} else if ("get1hData".equals(fun)) {
			time = 1;
			format = new SimpleDateFormat("yyyyMMddHHmm");
		} else if ("getmyhourData".equals(fun)) {
			time = getParaToInt("hour");
			if (time >= 24) {
				format = new SimpleDateFormat("yyyyMMddHH");
			} else {
				format = new SimpleDateFormat("yyyyMMddHHmm");
			}
		}

		Calendar cal = Calendar.getInstance();

		cal.setTime(new Date());
		cal.add(Calendar.HOUR, -time);

		Date datefrom = cal.getTime();

		Date dateto = new Date();

		if ("getHistData".equals(fun)) {
			String from = getPara("from");
			String to = getPara("to");

			SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd HH:mm");

			datefrom = format1.parse(from);

			dateto = format1.parse(to);
		}

		String sql = "select *,(select devicename from thing_user_device where userid = '" + (sessionUser != null ? sessionUser.getStr("userid") : "")
				+ "' and deviceid = thing_device_alldata.id) devicename from thing_device_alldata where recievedate >= '" + datefrom.getTime() + "' and recievedate < '" + dateto.getTime()
				+ "' and id in " + sn + " order by recievedate asc";
		List<DeviceModel> devices = DeviceModel.me.find(sql);
		// List<DeviceModel> devices =
		// DeviceModel.me.find("select * from thing_device_alldata where id in "
		// + sn + " order by recievedate asc");

		Map<String, Object> mmap = new HashMap<String, Object>();

		for (int i = 0; i < devices.size(); i++) {
			DeviceModel dmodel = devices.get(i);
			String id = dmodel.getStr("id");
			Date date = new Date(new Long(dmodel.getStr("recievedate")));
			mmap.put(id + format.format(date), dmodel);
		}

		Iterator<String> it = mmap.keySet().iterator();

		List<DeviceModel> returnlist = new ArrayList<DeviceModel>();

		while (it.hasNext()) {
			String key = it.next();
			DeviceModel dmodel = (DeviceModel) mmap.get(key);
			dmodel.set("recievedate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(dmodel.getStr("recievedate")))));
			returnlist.add(dmodel);
		}

		Map<String, Object> retmap = new HashMap<String, Object>();

		Collections.sort(returnlist, new Comparator<DeviceModel>() {
			@Override
			public int compare(DeviceModel o1, DeviceModel o2) {
				int i = 0;
				try {
					i = o1.getStr("id").compareTo(o2.getStr("id"));
					if (i == 0)
						i = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(o2.getStr("recievedate")).compareTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(o1.getStr("recievedate")));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return i;
			}
		});

		retmap.put("status", "ok");
		retmap.put("result", returnlist);

		renderJson(retmap);

	}

	public void directController() {
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "远程控制");
		render("controller.html");
	}

	public void submitConfigInfo() {
		String[] ids = getParaValues("deviceConfigure.id");
		CommonMsgBean msg = new CommonMsgBean();
		if (ids == null) {
			msg.setFlag(true);
			msg.setMsg("请选择更新的设备");
			renderJson(msg);
			return;
		}
		DeviceConfigure user = getModel(DeviceConfigure.class);
		System.out.println(user.get("time"));

		for (int i = 0; i < ids.length; i++) {
			DeviceConfigure userc = new DeviceConfigure();
			userc.setAttrs(user);
			userc.set("aftersetcount", 0);
			userc.set("id", ids[i]);
			boolean flag = userc.update();
			if (!flag) {
				flag = userc.save();
			}
		}
		msg.setFlag(true);
		msg.setMsg("更新成功");
		renderJson(msg);
	}

	public void getConfigInfo() {
		String id = getPara("id");

		// String s = DeviceConfigure.me.getConfigureinfotoStr(id);

		// System.out.println(s);

		DeviceConfigure user = DeviceConfigure.me.findById(id);
		if (user == null) {
			CommonMsgBean msg = new CommonMsgBean();
			msg.setFlag(true);
			msg.setMsg("没有数据！");
			renderJson(msg);
		} else {
			renderJson(user);
		}
	}

	// private Record addmodeltokey(Model user,String modelname){
	// Record record = new Record();
	// String[] names = user.getAttrNames();
	// for(int i = 0; i < names.length ; i++){
	// record.set(modelname +"."+ names[i], user.get(names[i]));
	// }
	// return record;
	// }

	@ClearInterceptor(ClearLayer.ALL)
	public void registerIndex() {
		render("register.html");
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void register() {

		User user = getModel(User.class);
		User userByEmail = User.me.findFirst("select * from thing_user where email = '" + user.getStr("email") + "'");
		User userByaccount = User.me.findFirst("select * from thing_user where account = '" + user.getStr("account") + "'");
		User userBymobile = User.me.findFirst("select * from thing_user where mobile = '" + user.getStr("mobile") + "'");
		CommonMsgBean msg = new CommonMsgBean();

		String enPassword = Util.encryptBasedDes(user.getStr("password"));

		if (userByEmail != null) {
			msg.setFlag(false);
			msg.setMsg("邮箱已经存在！");
		} else if (userByaccount != null) {
			msg.setFlag(false);
			msg.setMsg("用户名已经存在！");
		} else if (userBymobile != null) {
			msg.setFlag(false);
			msg.setMsg("手机已经存在！");
		} else {
			user.set("userid", Util.getKey());
			user.set("password", enPassword);

			boolean flag = user.save();
			if (flag) {
				user = user.findById(user.getStr("userid"));
				setSessionAttr("userinfo", user);
				setSessionAttr("username", user.getStr("username"));
				msg.setFlag(true);
				msg.setMsg("注册成功！");
			} else {
				msg.setMsg("注册失败！");
			}
		}
		renderJson(msg);
	}

	public void updateuserIndex() {
		setAttr("user", (User) getSession().getAttribute("userinfo"));
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "用户信息");
		render("userinfomanager.html");
	}

	public void updateuserinfo() {
		User user = getModel(User.class);

		User sessionUser = (User) getSession().getAttribute("userinfo");

		CommonMsgBean msg = new CommonMsgBean();

		String enPassword = Util.encryptBasedDes(getPara("confirmpassword"));

		if (!enPassword.equals(sessionUser.getStr("password"))) {
			msg.setMsg("密码错误！");
		} else {

			User userByEmail = User.me.findFirst("select * from thing_user where email = '" + user.getStr("email") + "' and userid != '" + sessionUser.getStr("userid") + "'");
			User userByaccount = User.me.findFirst("select * from thing_user where account = '" + user.getStr("account") + "'and userid != '" + sessionUser.getStr("userid") + "'");
			User userBymobile = User.me.findFirst("select * from thing_user where mobile = '" + user.getStr("mobile") + "'and userid != '" + sessionUser.getStr("userid") + "'");

			if (userByEmail != null) {
				msg.setFlag(false);
				msg.setMsg("邮箱已经存在！");
			} else if (userByaccount != null) {
				msg.setFlag(false);
				msg.setMsg("用户名已经存在！");
			} else if (userBymobile != null) {
				msg.setFlag(false);
				msg.setMsg("手机已经存在！");
			} else {
				user.set("userid", Util.getKey());

				if (user.getStr("password").equals(enPassword)) {
					user.set("password", enPassword);
				} else {
					user.set("password", Util.encryptBasedDes(user.getStr("password")));
				}

				user.set("userid", sessionUser.get("userid"));
				boolean flag = user.update();
				if (flag) {
					setSessionAttr("userinfo", user);
					setSessionAttr("username", user.getStr("username"));
					msg.setFlag(true);
					msg.setMsg("修改成功！");
				} else {
					msg.setMsg("修改失败！");
				}
			}
		}
		renderJson(msg);
	}

	public void directDeviceInfoIndex() {
		setAttr("user", (User) getSession().getAttribute("userinfo"));
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "部件配置");
		render("userdevicelist.html");
	}

	public void getDeviceInfo() {
		User user = (User) getSession().getAttribute("userinfo");

		List<UserDeviceModel> devices = UserDeviceModel.me.find("select * from thing_user_device where userid = '" + user.getStr("userid") + "'");

		for (UserDeviceModel deviceModel : devices) {
			deviceModel.put("detailaddress", ((deviceModel.get("province") != null) ? deviceModel.getStr("province") : "") + ((deviceModel.get("city") != null) ? deviceModel.getStr("city") : "")
					+ ((deviceModel.get("distinguish") != null) ? deviceModel.getStr("distinguish") : ""));
			
			String deviceid = deviceModel.get("deviceid");
			
			String first = deviceid.substring(0,2);
			Integer firstnum = Integer.parseInt(first, 16) * 256 * 256;
			String second = deviceid .substring(2,4);
			Integer secondnum = Integer.parseInt(second, 16) * 256;
			String three = deviceid.substring(4,6);
			Integer threenum = Integer.parseInt(three, 16);
			
			String idint = new Integer(firstnum + secondnum + threenum).toString();
			
			deviceModel.put("id", idint);
			
		}

		renderJson(devices);
	}

	public void updateUserDeviceInfo() {
		User user = (User) getSession().getAttribute("userinfo");
		UserDeviceModel userDeviceModel = getModel(UserDeviceModel.class);
		CommonMsgBean msg = new CommonMsgBean();
		String iseditorupdate = getPara("iseditorupdate");
		userDeviceModel.set("userid", user.getStr("userid"));
		try {
			Integer deviceid = Integer.parseInt(userDeviceModel.getStr("deviceid"));
			String hexdeviceid = Integer.toHexString(deviceid).toUpperCase();
			while(hexdeviceid.length() < 6){
				hexdeviceid = "0" + hexdeviceid;
			}
			userDeviceModel.set("deviceid", hexdeviceid);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		if (iseditorupdate.equals("add")) {
			UserDeviceModel userDeviceModelFromDB = userDeviceModel.me.findFirst("select * from thing_user_device where userid=? and deviceid=?", userDeviceModel.getStr("userid"),
					userDeviceModel.getStr("deviceid"));
			if (userDeviceModelFromDB != null) {
				msg.setMsg("机器已经存在，请不要重复添加！");
			} else {
				userDeviceModel.save();
				msg.setMsg("操作已成功！");
				msg.setFlag(true);
			}
		} else {
			int i = Db.update("update thing_user_device set devicename=? , province=?,city=?,distinguish=? where userid=? and deviceid=?", userDeviceModel.getStr("devicename"),
					userDeviceModel.getStr("province"), userDeviceModel.getStr("city"), userDeviceModel.getStr("distinguish"), userDeviceModel.getStr("userid"), userDeviceModel.getStr("deviceid"));
			msg.setMsg("操作已成功！");
			msg.setFlag(true);
		}

		renderJson(msg);
	}

	public void deleteUserDeviceInfo() {
		User user = (User) getSession().getAttribute("userinfo");
		UserDeviceModel userDeviceModel = getModel(UserDeviceModel.class);
		CommonMsgBean msg = new CommonMsgBean();

		userDeviceModel.set("userid", user.getStr("userid"));

		int i = Db.update("delete from thing_user_device where userid=? and deviceid=?", userDeviceModel.getStr("userid"), userDeviceModel.getStr("deviceid"));

		if (i == 1) {
			msg.setFlag(true);
			msg.setMsg("操作已成功！");
		} else {
			msg.setMsg("操作不成功！");
		}

		renderJson(msg);
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void directLineGraphic() {
		String id = getPara(0);
		String type = getPara(1, "pm25in");
		String uid = (String) getSession().getAttribute("uid");
		uid = uid == null ? "1" : uid;
		setAttr("id", id);
		setAttr("type", type);
		setAttr("uid", uid);
		render("line.html");
	}

	public void directFilterSettings() {
		setAttr("user", (User) getSession().getAttribute("userinfo"));
		setAttr("username", getSession().getAttribute("username")==null ? "游客" : getSession().getAttribute("username").toString());
		setAttr("type", "滤网设置");
		render("filterSettings.html");
	}

	public void submitFilterInfo() {
		String[] ids = getParaValues("deviceModel.id");
		CommonMsgBean msg = new CommonMsgBean();
		if (ids == null) {
			msg.setFlag(true);
			msg.setMsg("请选择更新的设备");
			renderJson(msg);
			return;
		}
		DeviceModel user = getModel(DeviceModel.class);
		System.out.println(user.get("time"));

		if (1 == user.getInt("primaryfilterlife_reset") || 1 == user.getInt("electrostaticdustoflife_reset") || 1 == user.getInt("highefficiencyfilterlife_reset")) {
			user.set("seton", 1);
		}

		for (int i = 0; i < ids.length; i++) {
			DeviceModel userc = new DeviceModel();
			userc.setAttrs(user);
			userc.set("id", ids[i]);
			boolean flag = userc.update();
			// if (!flag) {
			// flag = userc.save();
			// }
		}
		msg.setFlag(true);
		msg.setMsg("更新成功");
		renderJson(msg);
	}

	public void getFilterInfo() {
		String id = getPara("id");

		// String s = DeviceConfigure.me.getConfigureinfotoStr(id);

		// System.out.println(s);

		DeviceModel user = DeviceModel.me.findById(id);
		if (user == null) {
			CommonMsgBean msg = new CommonMsgBean();
			msg.setFlag(true);
			msg.setMsg("没有数据！");
			renderJson(msg);
		} else {
			renderJson(user);
		}
	}

	public void getFilterInfoAll() {
		User sessionuser = (User) getSession().getAttribute("userinfo");
		int isadmin = (int) sessionuser.getInt("isadmin");
		List<DeviceModel> users = null;
		if(isadmin == 1){
			users = DeviceModel.me.find("select * from thing_device"); 
			//Db.find("select a.*,(select devicename from thing_user_device where deviceid = a.id limit 1) devicename from thing_device a order by a.onoroff desc, a.id asc ");
		}else{
			users = DeviceModel.me.find("select a.* from thing_device a inner join thing_user_device b on a.id = b.deviceid where b.userid = ?",sessionuser.getStr("userid")); 
			//Db.find("select a.*,(select devicename from thing_user_device where deviceid = a.id limit 1) devicename from thing_device a inner join thing_user_device b on a.id = b.deviceid where b.userid = ? order by a.onoroff desc, a.id asc ",sessionuser.getStr("userid"));
		}
		
		//List<DeviceModel> users = DeviceModel.me.find("select * from thing_device");
		if (users == null) {
			CommonMsgBean msg = new CommonMsgBean();
			msg.setFlag(true);
			msg.setMsg("没有数据！");
			renderJson(msg);
		} else {
			
			for(DeviceModel user : users){
				
				String deviceid = user.get("id");
				
				String first = deviceid.substring(0,2);
				Integer firstnum = Integer.parseInt(first, 16) * 256 * 256;
				String second = deviceid .substring(2,4);
				Integer secondnum = Integer.parseInt(second, 16) * 256;
				String three = deviceid.substring(4,6);
				Integer threenum = Integer.parseInt(three, 16);
				
				String idint = new Integer(firstnum + secondnum + threenum).toString();
				
				user.put("mid", idint);
			}
			
			
			renderJson(users);
		}
	}

	public void submitquery() {
		String id = getPara("id");
		DeviceModel user = new DeviceModel();
		user.set("id", id);
		user.set("queryon", 1);
		user.update();
		CommonMsgBean msg = new CommonMsgBean();
		msg.setFlag(true);
		msg.setMsg("服务器一开始执行查询，稍后查询设备返回数据！");
		renderJson(msg);
	}

}
